<script setup>
import { reactive, ref, toRefs } from 'vue';
import { ElMessage } from 'element-plus';
import { loginService,registerService } from '@/api/auth';
import { useTokenStore } from '@/stores/token.js';
import router from '@/router';
import axios from 'axios';


const tokenStore = useTokenStore();
const drawer = ref(false); // 注册抽屉
const adminDrawer = ref(false); // 管理员登录抽屉
const direction = ref('rtl');
const registerForm = ref(null);
const adminForm = ref(null); // 添加这一行
const registerData = ref({
  phone: '',
  password: '',
  name: '',
});
const adminData = ref({
  username: '',
  password: '',
});
const validatePhone = (rule, value, callback) => {
  const phoneRegex = /^1[3456789]\d{9}$/;
  if (!value) {
    callback(new Error('请输入手机号'));
  } else if (!phoneRegex.test(value)) {
    callback(new Error('手机号必须为11位数字'));
  } else {
    callback();
  }
};
const validateUsername = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入用户名'));
  } else {
    callback();
  }
};
const registerRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { validator: validatePhone, message: '11位数字', trigger: 'blur' },
  ],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
};
const adminRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { validator: validatePhone, trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 5, max: 16, message: '密码长度为5~16位', trigger: 'blur' },
  ],
};
const state = reactive({
  circleUrl: 'https://img2.baidu.com/it/u=3926734404,2114692953&fm=253&fmt=auto&app=138&f=JPEG?w=807&h=800',
});
const { circleUrl } = toRefs(state);
const loginForm = ref(null);
const loginData = ref({
  phone: '',
  password: '',
});
const loginRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { validator: validatePhone, message: '11位数字', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 5, max: 16, message: '密码长度为5~16位', trigger: 'blur' },
  ],
};

const register = async () => {
  const valid = await registerForm.value.validate();
  if (valid) {
    try {
      const result = await registerService(registerData.value);
      ElMessage.success('注册成功');
      drawer.value = false;
    } catch (error) {
      console.error('注册失败:', error);
      ElMessage.error('注册失败，请稍后再试');
    }
  } else {
    ElMessage.error('请检查表单信息');
  }
};

const login = async () => {
  const valid = await loginForm.value.validate();
  if (valid) {
    try {
      const result = await loginService(loginData.value);
      tokenStore.setToken(result.data);
      console.log('当前 token:', tokenStore.token);
      router.push('/home');
      ElMessage.success('登录成功');
    } catch (error) {
      console.error('登录失败:', error);
      ElMessage.error('登录失败，请稍后再试');
    }
  } else {
    ElMessage.error('请检查表单信息');
  }
};

const adminLogin = async () => {
  const valid = await adminForm.value.validate();
  if (valid) {
    try {
      const response = await axios.post('http://localhost:8080/auth/login', {
        phone: adminData.value.phone,
        password: adminData.value.password,
      });

      // 检查后端返回的数据
      if (response.data && response.data.code === 0 && response.data.data) {
        const { token, user } = response.data.data;

        // 保存 token 和角色信息
        tokenStore.setToken(token);
        localStorage.setItem('role', user.role);

        // 根据角色跳转
        if (user.role === 1) { // 管理员的 role 是 1
          router.push('/AdminHome');
          ElMessage.success('管理员登录成功');
        } else {
          ElMessage.error('登录失败：您不是管理员');
        }
      } else {
        // 如果后端返回的 code 不为 0 或 data 为空
        ElMessage.error('登录失败：' + (response.data.message || '未知错误'));
      }
    } catch (error) {
      console.error('登录失败:', error);
      ElMessage.error(error.response?.data?.message || '登录失败，请稍后再试');
    }
  } else {
    ElMessage.error('请检查表单信息');
  }
};
</script>

<template>
  <div id="background">
    <el-row id="login">
      <el-col :span="9" id="left">
        <div id="avatar">
          <el-avatar :size="150" :src="circleUrl" fit="cover" />
        </div>
        <el-text id="WELCOME">WELCOME</el-text>
      </el-col>
      <el-col :span="15" id="right">
        <el-form ref="loginForm" size="large" autocomplete="off" :model="loginData" :rules="loginRules">
          <el-form-item prop="phone" id="inputPhone">
            <input class="rounded-input" placeholder=" 手机号:" v-model="loginData.phone">
          </el-form-item>
          <el-form-item prop="password" id="inputPassword">
            <input type="password" class="rounded-input" placeholder=" 密  码:" v-model="loginData.password">
          </el-form-item>
          <el-form-item class="flex">
            <div class="flex">
              <button class="registerButton" type="button" @click="drawer = true">
                注册账号
              </button>
              <button class="registerButton" type="button" @click="adminDrawer = true">
                管理员登录
              </button>
            </div>
          </el-form-item>
          <el-form-item id="loginButton">
            <el-button id="button1" @click="login">立 即 登 录</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-drawer v-model="drawer" :direction="direction">
        <el-form ref="registerForm" :model="registerData" :rules="registerRules" label-width="80px">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="registerData.phone" placeholder="请输入手机号" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="registerData.password" placeholder="请输入密码" show-password />
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="registerData.name" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="register">注册</el-button>
            <el-button @click="drawer = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-drawer>
      <el-drawer v-model="adminDrawer" :direction="direction" title="管理员登录">
        <el-form ref="adminForm" :model="adminData" :rules="adminRules" label-width="80px">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="adminData.phone" placeholder="请输入手机号" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="adminData.password" placeholder="请输入密码" show-password />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="adminLogin">登录</el-button>
            <el-button @click="adminDrawer = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-drawer>
    </el-row>
  </div>
</template>

<style scoped>
#background {
  height: 100vh;
  width: 100%;
  background-image: url("@/assets/images/login_background.jpg");
  background-size: 100% 100%;
}

#login {
  height: 45%;
  width: 38%;
  position: absolute;
  top: 0;
  bottom: 10%;
  left: 45%;
  right: 0;
  margin: auto;
  background-color: rgba(127, 127, 127, 0.25);
  border-radius: 40px;
  border-color: #D9D9D9;
  border-style: solid;
  border-width: 5px;
}

#left {
  border-right: 5px solid #D9D9D9;
  border-top-left-radius: 30px;
  border-bottom-left-radius: 25px;
}

#avatar {
  width: 100%;
  height: auto;
  margin-top: 25%;
  display: flex;
  justify-content: center;
}

#WELCOME {
  font-size: 2rem;
  font-family: Tahoma, serif;
  color: #FFFFFF;
  margin-top: 25%;
  display: flex;
  justify-content: center;
}

#inputPhone {
  width: 60%;
  height: 20%;
  margin-top: 20%;
  margin-left: 50%;
  transform: translateX(-50%);
}

#inputPassword {
  width: 60%;
  margin-top: 10%;
  margin-left: 50%;
  transform: translateX(-50%);
}

.rounded-input {
  width: 100%;
  height: 175%;
  border: none;
  border-radius: 40px;
  background-color: rgba(255, 255, 255, 0.7);
  color: rgb(127, 127, 127);
  text-align: center;
}

.rounded-input:focus {
  outline: none;
  border: none;
}

.flex {
  width: 120%;
  margin-top: 5%;
  margin-left: 50%;
  transform: translateX(-50%);
  display: flex;
  justify-content: space-between;
}

.registerButton {
  background: none;
  border: none;
  color: #FFFFFF;
  cursor: pointer;
}

#loginButton {
  width: 40%;
  height: 10%;
  margin-left: 50%;
  transform: translateX(-50%);
}

#button1 {
  width: 100%;
  border: none;
  border-radius: 35px;
  background-color: rgba(51, 63, 80, 0.7);
  color: #FFFFFF;
}
</style>
<style>
.myCheckBox.is-bordered.is-checked {
  border-color: rgba(51, 63, 80, 0.7);
}

.myCheckBox .el-checkbox__input.is-checked + .el-checkbox__label {
  color: rgba(51, 63, 80, 0.7);
}

.myCheckBox .el-checkbox__input.is-checked .el-checkbox__inner,
.myRedCheckBox .el-checkbox__input.is-indeterminate .el-checkbox__inner {
  border-color: rgba(51, 63, 80, 0.7);
  background-color: rgba(51, 63, 80, 0.7);
}

.myCheckBox .el-checkbox__input.is-focus .el-checkbox__inner {
  border-color: rgba(51, 63, 80, 0.7);
}
</style>